﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ModifyEpisode : System.Web.UI.Page
{
    ManageDatabase data;
    Episode episode;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated)
        {
            episode = new Episode();

            if (data == null)
            {
                data = new ManageDatabase();
            }
            if (!IsPostBack)
            {
                if (Request.QueryString["epizod"] != null)
                {
                    GetSeries();

                    InitLenth();

                    String s = Request.QueryString["epizod"].ToString();
                    InitializeEdit(Convert.ToInt32(s));
                }
                else
                {
                    Response.Redirect("~/Default.aspx");
                }
                Page.Form.Attributes.Add("enctype", "multipart/form-data"); 
            }
        }
        else
        {
            Response.Redirect("~/Default.aspx");
        }
    }

    private void InitLenth()
    {
        for (int i = 0; i < 3; i++)
        {
            AddEpisodeLengthHours.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
        for (int i = 0; i < 60; i++)
        {
            AddEpisodeLengthMinutes.Items.Add(new ListItem(i.ToString(), i.ToString()));
            AddEpisodeLengthSeconds.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
    }

    private void GetSeries()
    {
        ListItemCollection allSeries = data.GetSeriesSimple();
        AddEpisodeChooseSeries.Items.Clear();
        AddEpisodeChooseSeries.Items.Add(new ListItem("--Válasszon sorozatot--", "0"));
        AddEpisodeChooseSeason.Items.Add(new ListItem("--Válasszon évadot--", "0"));
        foreach (ListItem item in allSeries)
        {
            AddEpisodeChooseSeries.Items.Add(item);
        }
    }


    protected void AddEpisodeChooseSeries_SelectedIndexChanged(object sender, EventArgs e)
    {
        int series_id = Convert.ToInt32(AddEpisodeChooseSeries.SelectedValue);
        if (series_id == 0)
        {
            AddEpisodeChooseSeason.Items.Clear();
            AddEpisodeChooseSeason.Items.Add(new ListItem("--Válasszon évadot--", "0"));
        }
        else
        {
            ListItemCollection allSeason = data.GetSeasonsSimple(series_id);
            AddEpisodeChooseSeason.Items.Clear();
            AddEpisodeChooseSeason.Items.Add(new ListItem("--Válasszon évadot--", "0"));
            foreach (ListItem item in allSeason)
            {
                AddEpisodeChooseSeason.Items.Add(item);
            }
        }
    }

    protected void EpisodeModify_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.QueryString["epizod"] != null)
            {
                String s = Request.QueryString["epizod"].ToString();
                episode.id = Convert.ToInt32(s);
            }
            else
            {
                return;
            }
            if (AddEpisodeChooseSeries.SelectedValue == "0")
            {
                Alert.Show("Kérem válasszon ki egy sorozatot!");
                return;
            }
            else
            {
                episode.seriesId = Convert.ToInt32(AddEpisodeChooseSeries.SelectedValue);
            }
            if (AddEpisodeChooseSeason.SelectedValue == "0")
            {
                Alert.Show("Kérem válasszon ki egy évadot!");
                return;
            }
            else
            {
                episode.seasonId = Convert.ToInt32(AddEpisodeChooseSeason.SelectedValue);
            }

            try
            {
                episode.episode = Convert.ToInt32(AddEpisodeNumber.Text);
            }
            catch (Exception)
            {
                Alert.Show("Az évad száma csak numerikus lehet!");
                return;
            }

            episode.titleHun = AddEpisodeTitleHun.Text;
            episode.titleOrig = AddEpisodeTitleOrig.Text;
            if (episode.titleHun == "" || episode.titleHun == " ")
            {
                Alert.Show("Kérem adja meg az epizód címét!");
                return;
            }

            if (AddEpisodeReleaseDate.Text != "")
            {
                try
                {
                    episode.releaseDate = DateTime.Parse(AddEpisodeReleaseDate.Text);
                }
                catch (Exception)
                {
                    Alert.Show("Érvénytelen a megjelenés dátuma!");
                    return;
                }
            }

            episode.length = (Convert.ToInt32(AddEpisodeLengthHours.SelectedValue) * 3600) +
                                (Convert.ToInt32(AddEpisodeLengthMinutes.SelectedValue) * 60) +
                                (Convert.ToInt32(AddEpisodeLengthSeconds.SelectedValue));

            episode.videoUrl = AddEpisodeEmbedVideo.Text;
            episode.description = AddEpisodeDescription.Text;

            bool ImgWasChanged = false;
            episode.imgUrl = "";

            if (AddEpisodeKeepImgCheck.Checked)
            {
                if (AddEpisodeImg.HasFile)
                {
                    try
                    {
                        if (AddEpisodeImg.PostedFile.ContentType == "image/pjpeg" || AddEpisodeImg.PostedFile.ContentType == "image/x-jpeg") //image/gif,image/x-png
                        {
                            if (AddEpisodeImg.PostedFile.ContentLength < 512000)
                            {
                                string filename = "episode_" + String.Format("{0:yyyyMMddhhmmss}", DateTime.Now) + ".jpeg";
                                AddEpisodeImg.SaveAs(Server.MapPath("~/Pic/") + filename);
                                episode.imgUrl = filename;
                                ImgWasChanged = true;
                            }
                            else
                            {
                                StatusLabel.Text = "A maximális képméret 500 kb!";
                                return;
                            }
                        }
                        else
                        {
                            StatusLabel.Text = "Az alábbi képformátum nem támogatott: " + AddEpisodeImg.PostedFile.ContentType;
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        StatusLabel.Text = "Hiba történt a kép feltöltése során.";
                        return;
                    }
                }
            }
            else
            {
                ImgWasChanged = false;
            }

            Boolean success = data.UpdateEpisode(episode, ImgWasChanged);

            if (!success)
            {
                Alert.Show("Hiba történt az éved létrehozása során!");
            }
            else
            {
                Response.Redirect("~/Series.aspx");
            }
        }
        catch (Exception)
        {
            Alert.Show("Hiba történt az éved létrehozása során!");
        }
    }

    protected void EpisodeCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Series.aspx");
    }

    private void InitializeEdit(int id)
    {
        episode = data.GetWholeEpisode(id, true);
        if (!User.IsInRole("admin") && Functions.GetUserId() != episode.userID && episode.status != 1)
        {
            Response.Redirect("~/Default.aspx");
        }
        else
        {
            AddEpisodeChooseSeries.Items.FindByValue(episode.seriesId.ToString()).Selected = true;
            ListItemCollection allSeason = data.GetSeasonsSimple(episode.seriesId);
            AddEpisodeChooseSeason.Items.Clear();
            AddEpisodeChooseSeason.Items.Add(new ListItem("--Válasszon évadot--", "0"));
            foreach (ListItem item in allSeason)
            {
                AddEpisodeChooseSeason.Items.Add(item);
            }
            AddEpisodeChooseSeason.Items.FindByValue(episode.seasonId.ToString()).Selected = true;
            AddEpisodeNumber.Text = episode.episode.ToString();
            AddEpisodeTitleHun.Text = episode.titleHun;
            AddEpisodeTitleOrig.Text = episode.titleOrig;
            AddEpisodeDescription.Text = episode.description;
            AddEpisodeEmbedVideo.Text = episode.videoUrl;
            DateTime nullDate = new DateTime(1800, 01, 01);
            if (!episode.releaseDate.Equals(nullDate))
            {
                AddEpisodeReleaseDate.Text = String.Format("{0:yyyy-MM-dd}", episode.releaseDate);
            }
            if (Convert.ToInt32(episode.length) != 0)
            {
                int seconds = Convert.ToInt32(episode.length);
                int hours = 0, minutes = 0;

                hours = seconds / 3600;
                if (hours == 0)
                {
                    minutes = seconds / 60;
                    if (minutes == 0)
                    {
                        AddEpisodeLengthSeconds.Items.FindByValue(seconds.ToString()).Selected = true;
                    }
                    else
                    {
                        seconds = seconds - minutes * 60;
                        AddEpisodeLengthMinutes.Items.FindByValue(minutes.ToString()).Selected = true;
                        AddEpisodeLengthSeconds.Items.FindByValue(seconds.ToString()).Selected = true;
                    }
                }
                else
                {
                    minutes = (seconds - hours * 3600) / 60;
                    seconds = seconds - hours * 3600 - minutes * 60;
                    AddEpisodeLengthHours.Items.FindByValue(hours.ToString()).Selected = true;
                    AddEpisodeLengthMinutes.Items.FindByValue(minutes.ToString()).Selected = true;
                    AddEpisodeLengthSeconds.Items.FindByValue(seconds.ToString()).Selected = true;
                }
            }
            if (!String.IsNullOrEmpty(episode.imgUrl))
            {
                AddEpisodeKeepImg.ImageUrl = "~/Pic/" + episode.imgUrl;
            }
        }
    }

    protected void AddEpisodeKeepImgCheck_CheckedChanged(object sender, EventArgs e)
    {
        if (AddEpisodeKeepImgCheck.Checked)
        {
            AddEpisodeKeepImgDiv.Visible = false;
            AddEpisodeChangeImgDiv.Visible = true;
        }
        else
        {
            AddEpisodeChangeImgDiv.Visible = false;
            AddEpisodeKeepImgDiv.Visible = true;
        }
    }
}